package com.csnf.servlet;

import com.csnf.dao.IStudentDao;
import com.csnf.dao.impl.StudentDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet({"/StudentServlet","/deleteById","/getStudentById"})
public class StudentServlet  extends HttpServlet {
    IStudentDao studentDao = new StudentDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取servlet路径
        String servletPath = req.getServletPath();
        switch (servletPath){
            //根据id查询学生信息
            case "/getStudentById":
                req.setAttribute("students", studentDao.findById(Integer.parseInt(req.getParameter("sId"))));
                req.getRequestDispatcher("editStudent.jsp").forward(req, resp);
                break;
            //根据id删除学生信息
            case "/deleteById":
                studentDao.deleteById(Integer.parseInt(req.getParameter("sId")));
                req.setAttribute("students", studentDao.findAll());
                break;
            // 查询学生信息
            case "/StudentServlet":
                String sName = req.getParameter("sName");
                //判断是否为空 如果是空则查询所有，否则根据姓名查询
                if(sName!=null){
                    req.setAttribute("students", studentDao.findByName(sName));
                }else{
                    req.setAttribute("students", studentDao.findAll());
                }
                break;
        }
        req.getRequestDispatcher("student.jsp").forward(req, resp);
    }
}